<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jsjac.js"></script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
// <![CDATA[

var tabManager=new Array();
var tabUrlManager=new Array();
var EvenQueue=new Array();
var MsgSession=new Array();
var Context=new Array();
var joinedRooms=new Array();
var roomToUrl=new Array();
var ActiveSession="";
var iconcount=0;
var urlist=['http:\/\/item.taobao.com\/*','http:\/\/detail.tmall.com\/*','http:\/\/www.360buy.com\/product\/*'];
function matchurl(url){
    for(var i=0;i<urlist.length;i++)
	{
	    var re=new RegExp(urlist[i]);
	    if(url.match(re)!=null)
		   return true;
	}
	return false;
}
function OnOpenTab(tabId,chanInfo,tab){
    if(tab.status=="complete"){
	    var lasturl="";
		if('undefined' == typeof tabManager[tabId]){
	        tabManager[tabId]=tab.url;
		}
		else{
		    lasturl=tabManager[tabId];
			tabManager[tabId]=tab.url;
		    delete tabUrlManager[lasturl];
		}
		var urlinfo=new Object();
		urlinfo.url=tab.url;
		urlinfo.title=tab.title;
		urlinfo.favIconUrl=tab.favIconUrl;
		urlinfo.timestamp=Date.parse(new Date());
	    tabUrlManager[tab.url]=urlinfo;
    }
}
function OnCloseTab(tabId,removeInfo){
    var url=tabManager[tabId];
	delete tabUrlManager[url];
	delete joinedRooms[url];
	delete tabManager[tabId];
}

function OnMessage(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
	if(request.cmd=='thirdlogin'){
	    doLogin(request.data);
	}
    chrome.windows.remove(sender.tab.windowId,function(){});
}

function handleIQ(aIQ) {
    con.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
}

function handleMessage(aJSJaCPacket) {
    var roomid=aJSJaCPacket.getFromJID().getNode();
	if('undefined'==typeof MsgSession[roomToUrl[roomid]]){
	    MsgSession[roomToUrl[roomid]]=new Array();
	}
	MsgSession[roomToUrl[roomid]].push(aJSJaCPacket);
/*	var qstr=encodeURIComponent(aJSJaCPacket.getBody().htmlEnc());
	var noticeURL = chrome.extension.getURL('incomingnotify.html') + "?msg=" + qstr;
	var notification = webkitNotifications.createHTMLNotification(noticeURL);
	notification.show();*/
}

function handlePresence(aJSJaCPacket) {
    var event=new Object();
	event.handler='handlePresence';
	event.body=aJSJaCPacket;
	EvenQueue.push(event);
	var jid=aJSJaCPacket.getFromJID();
	var room=jid.getNode();
	var qstr=encodeURIComponent(roomToUrl[room]);
	var noticeURL = chrome.extension.getURL('presentnotify.html') + "?url=" + qstr;
	var notification = webkitNotifications.createHTMLNotification(notificationURL);
	notification.show();
}

function handleError(e) {
  
    if (con.connected())
        con.disconnect();
	oDbg.log("error"+"code:"+e.getAttribute('code')+" type:"+e.getAttribute('type'));
	var event=new Object();
	event.handler='handleError';
	event.body=e;
	EvenQueue.push(event);
}

function handleStatusChanged(status) {
    oDbg.log("status changed: "+status);
  	var event=new Object();
	event.handler='handleStatusChanged';
	event.body=status;
	EvenQueue.push(event);
}

function handleConnected() {

    oDbg.log("connected");
    con.send(new JSJaCPresence());
	testAndJoinRoom(true);
    setInterval("onOneSecondClock()",1000);
    var event=new Object();
	event.handler='handleConnected';
	EvenQueue.push(event);
	
}

function handleDisconnected() {
    oDbg.log("disconnected");
    var event=new Object();
	event.handler='handleDisconnected';
	EvenQueue.push(event);
}

function handleIqVersion(iq) {
  con.send(iq.reply([
                     iq.buildNode('name', 'jsjac simpleclient'),
                     iq.buildNode('version', JSJaC.Version),
                     iq.buildNode('os', navigator.userAgent)
                     ]));
  return true;
}

function handleIqTime(iq) {
  var now = new Date();
  con.send(iq.reply([iq.buildNode('display',
                                  now.toLocaleString()),
                     iq.buildNode('utc',
                                  now.jabberDate()),
                     iq.buildNode('tz',
                                  now.toLocaleString().substring(now.toLocaleString().lastIndexOf(' ')+1))
                     ]));
  return true;
}

function doLogin(aForm) {
    return connect(aForm);
}

function setupCon(con) {
    con.registerHandler('message',handleMessage);
    con.registerHandler('presence',handlePresence);
    con.registerHandler('iq',handleIQ);
    con.registerHandler('onconnect',handleConnected);
    con.registerHandler('onerror',handleError);
    con.registerHandler('status_changed',handleStatusChanged);
    con.registerHandler('ondisconnect',handleDisconnected);

    con.registerIQGet('query', NS_VERSION, handleIqVersion);
    con.registerIQGet('query', NS_TIME, handleIqTime);
}
function binaryToBlob(data) {
    var BlobBuilder = BlobBuilder || WebKitBlobBuilder || MozBlobBuilder;
    var bb = new BlobBuilder();
    var arr = new Uint8Array(data.length);
    for(var i = 0, l = data.length; i < l; i++) {
        arr[i] = data.charCodeAt(i);
    }
    bb.append(arr.buffer);
    return bb.getBlob();
}
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
    function byteValue(x) {
        return x.charCodeAt(0) & 0xff;
    }
    var ords = Array.prototype.map.call(datastr, byteValue);
    var ui8a = new Uint8Array(ords);
    this.send(ui8a.buffer);
}
function sendMsg(aForm) {
  if (aForm.sendTo.value == '')
    return false;
  var framedoc=aForm.children[1].firstChild.contentDocument;
  var imgs=framedoc.getElementsByTagName('img');
  for(var i=0;i<imgs.length;i++){
      var r = new XMLHttpRequest();
	  r.open("GET",imgs[i].src,false);
	  r.overrideMimeType('text/plain; charset=x-user-defined');
	  r.send(null);
	  
	  try{
	  var rpost=new XMLHttpRequest();
	  rpost.open("POST","http://ec2-174-129-162-239.compute-1.amazonaws.com/upload.php",false);
	  rpost.setRequestHeader("Content-Type","application/octet-stream");
	  //rpost.setRequestHeader("Content-Length",r.response.length);
	  //rpost.setRequestHeader("Connection","close");*/
	  //rpost.overrideMimeType("application/octet-stream");
	  //rpost.sendAsBinary(reader.result);
	  rpost.onreadystatechange=function(){
	      if(rpost.readyState==4){
		      imgs[i].src=rpost.responseText;
		  }
	  }
	  rpost.sendAsBinary(r.responseText);
	  }
	  catch(e){
	      alert(e);
	  }
  }
  var msg=aForm.children[1].firstChild.contentDocument.body.innerHTML;
  if(msg=='')
    return false;
  if (aForm.sendTo.value.indexOf('@') == -1)
    aForm.sendTo.value += '@' + con.domain;

  try {
      var aMsg = new JSJaCMessage();
	  var mNode = aMsg.getNode();
	  mNode.setAttribute('type','groupchat') 
      aMsg.setTo(new JSJaCJID(aForm.sendTo.value));
      aMsg.setBody(msg);
      con.send(aMsg);

      aForm.children[1].firstChild.contentDocument.body.innerHTML = '';
      return true;
  }catch (e) {
      throw e;
  }
}

function OnjoinRoomSend(data)
{
    console.log(data.getDoc());
	  var RoomJID=data.getFrom();
    var iq=new JSJaCIQ();
    iq.setIQ(RoomJID,'set',con.username);
	  var query=iq.setQuery('http://jabber.org/protocol/muc#owner');
	  query.appendChild(iq.buildNode('x',{xmlns:'jabber:x:data',type: 'submit'}));
    con.send(iq,function(data){console.log(data.getDoc());});
}
function joinRoom(RoomJID)
{
    try{
        var joinPacket = new JSJaCPresence();
	    joinPacket.setTo(new JSJaCJID(RoomJID+'@conference.'+con.domain+'/'+con.username));

	    //Build item affiliation element
        //var inode = joinPacket.buildNode("item");
        //inode.setAttribute("affiliation","none");
        //inode.setAttribute("jid",con.username);
        //inode.setAttribute("role","participant");

        //Build X Element (with item affiliation child)
        //var xnode = joinPacket.buildNode("x", [inode]);
		var xnode = joinPacket.buildNode("x");
        xnode.setAttribute("xmlns", "http://jabber.org/protocol/muc");

        //Append new nodes to join packet
        joinPacket.appendNode(xnode);

        //Set status in room
        //joinPacket.setStatus('available');
        
		if(!connected() && !connectresume() && !connect()){
		    
        }
        if(connected()){
		    con.send(joinPacket, OnjoinRoomSend);
        }
		
	}
	catch(e){
	    return false;
	}
	return true;
}
function StoreHistory(url){
    if (window.localStorage) {
	    if(window.localStorage['history']){
		    var data=window.localStorage['history'];
			var history=JSON.parse(data);
			history.push(tabUrlManager[url]);
			window.localStorage['history']=JSON.stringify(history);
		}
		else{
		    var data=new Array();
			data.push(tabUrlManager[url]);
			window.localStorage['history']=JSON.stringify(data);
		}
	}
}
function GetHistory(){
    if (window.localStorage) {
	    if(window.localStorage['history']){
		    var data=window.localStorage['history'];
			var temp=JSON.parse(data);
			var history=new Array();
			for(i=temp.length-1;i>=0;i--){
			    history[temp[i].url]=temp[i];
			}
		    return history;
		}
	}
}
function testAndJoinRoom(resume){
	for(key in tabUrlManager){
	    var url=key;
		var timestamp=tabUrlManager[key].timestamp;
		var now=Date.parse(new Date());
		if(now-timestamp<10)
		    continue;
		var re=new RegExp(/http:\/\/item.taobao.com\/*/);
		if(!matchurl(url)){
		    continue;
		}
		if(typeof joinedRooms[url]!='undefined' && !resume)
		    continue;
		var ret=joinRoom(url.replace(/[\.\/\?:=&]/g,''));
		if(ret==true){
		    joinedRooms[url]=url.replace(/[\.\/\?:=&]/g,'');
			roomToUrl[url.replace(/[\.\/\?:=&]/g,'')]=url;
			StoreHistory(url);
		}
	}
}
function updateIcon(){
    iconcount=iconcount==0 ? 1:0;
	var hasmsg=false;
    for(key in MsgSession){
	    if(MsgSession[key].length>0){
		    hasmsg=true;
			break;
		}
	}
	if(hasmsg){
	    if(iconcount==0)
		    chrome.browserAction.setIcon({path:'msg.jpg'});
		else
			chrome.browserAction.setIcon({path:'popup.jpg'});
	}
	else{
	    chrome.browserAction.setIcon({path:'popup.jpg'});
	}
}
function onOneSecondClock(){
    if(connected()){
	    testAndJoinRoom(false)
	}
	updateIcon();
}
function getDomain(){
    return con.domain;
}
function getUsrName(){
    return con.username;
}
function quit() {
  var p = new JSJaCPresence();
  p.setType("unavailable");
  con.send(p);
  con.disconnect();
}
function connectresume() {
    try{
	    con = new JSJaCHttpBindingConnection({'oDbg':oDbg});
		setupCon(con);
        if(!con.resume())
		    return false;
	}
	catch(e){
	    return false;
	}
	return true
}
function reconnect() {
    try{
        if(JSJaCCookie.read('username').getValue() && JSJaCCookie.read('pass').getValue()){
	        oArgs = new Object();
            oArgs.httpbase = "http://ec2-174-129-162-239.compute-1.amazonaws.com/xmpp-httpbind/";
            oArgs.timerval = 1000;
			if (typeof(oDbg) != 'undefined')
                oArgs.oDbg = oDbg;
	        con = new JSJaCHttpBindingConnection(oArgs);
	        setupCon(con);
            
            // setup args for connect method
            oArgs = new Object();
            oArgs.domain = "ec2-174-129-162-239.compute-1.amazonaws.com";
            oArgs.username = JSJaCCookie.read('username').getValue();
            oArgs.resource = oArgs.username;
            oArgs.pass = JSJaCCookie.read('pass').getValue();
            oArgs.register = false;
	        oArgs.authtype = "nonsasl";
            con.connect(oArgs)
		}
	}catch(e){return false;}
    return true;
}
function connect(aForm) {
    try{
	    oArgs = new Object();
        oArgs.httpbase = "http://ec2-174-129-162-239.compute-1.amazonaws.com/xmpp-httpbind/";
        oArgs.timerval = 1000;
	    if (typeof(oDbg) != 'undefined')
            oArgs.oDbg = oDbg;
	    con = new JSJaCHttpBindingConnection(oArgs);
	    setupCon(con);
        
        // setup args for connect method
        oArgs = new Object();
        oArgs.domain = "ec2-174-129-162-239.compute-1.amazonaws.com";
        oArgs.username = aForm.username.value;
        oArgs.resource = aForm.username.value;
        oArgs.pass = aForm.password.value;
        oArgs.register = false;
	    oArgs.authtype = "nonsasl";
        con.connect(oArgs);
	    (new JSJaCCookie('username',con.username)).write();
	    (new JSJaCCookie('pass',con.pass)).write();
	}catch(e){return false;}
    return true;
}
function connected(){
    if(con && con.connected()){
	    return true;
	}
	return false;
}
function init() {
    if (typeof(Debugger) == 'function') {
      oDbg = new Debugger(2,'simpleclient');
      oDbg.start();
    } else {
      // if you're using firebug or safari, use this for debugging
      //oDbg = new JSJaCConsoleLogger(2);
      // comment in above and remove comments below if you don't need debugging
      oDbg = console;
      //oDbg.log = console.log;
    }
	if(!connectresume()){
	    connect();
	}
}
onload = init;

onerror = function(e) { 
  if (con && con.connected())
    con.disconnect();
  return false; 
};

onunload = function() {
  if (typeof con != 'undefined' && con && con.connected()) {
  // save backend type
    if (con._hold) {// must be binding
      (new JSJaCCookie('btype','binding')).write();
	}
    else{
		(new JSJaCCookie('btype','polling')).write();
	}
	(new JSJaCCookie('username',con.username)).write();
	(new JSJaCCookie('pass',con.pass)).write();
    if (con.suspend) {
      con.suspend(); 
    }
  }
};

chrome.tabs.onRemoved.addListener(OnCloseTab);
chrome.tabs.onUpdated.addListener(OnOpenTab);
chrome.extension.onRequest.addListener(OnMessage);
// ]]>
</script>
</body>
</html>